//
//  XHNotificationManager.m
//  XHNotificationManager
//
//  Created by 曾 宪华 on 13-12-10.
//  Copyright (c) 2013年 曾宪华 开发团队(http://iyilunba.com ) 本人QQ:543413507. All rights reserved.
//

#import "XHNotificationManager.h"

static NSString* const DeviceTokenKey = @"DeviceToken";

@implementation XHNotificationManager

#pragma mark - Public api
// payload is received if the app is not running, a remote notifications is received and the app is opened as a result of the notification open tap
+ (void)showAlertMessageForLaunchOptionsDictionary:(NSDictionary *)launchOptions {
    NSDictionary *payload = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if(payload != nil)
    {
        NSDictionary *dict = [payload objectForKey:@"aps"];
        NSLog(@"%@", dict);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Message" message: [dict objectForKey:@"alert"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    } else {
        NSLog(@"这个时候是直接启动");
    }
}

+ (void)registerTheAppForPushNotifications:(UIApplication *)application {
    UIRemoteNotificationType notifType = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    [application registerForRemoteNotificationTypes:notifType];
    application.applicationIconBadgeNumber = 0;
}

+ (void)registerTheAppForPushNotifications:(UIApplication *)application WithNotificationType:(XHNotificationManagerType)notificationManagerType {
    switch (notificationManagerType) {
        case kXHAPNSNotification:
            // 远程通知
            [self registerTheAppForPushNotifications:application];
            break;
        case kXHLocalNotification:
            // 本地通知
            break;
        default:
            break;
    }
}

// the method should be called when a notifications is received and the app runs in the foreground
// 在app运行在前台和接收到通知的时候，就需要调用这个方法
+ (void)showReceivedRemoteNotificationForapplication:(UIApplication *)application UserInfo:(NSDictionary *)userInfo {
    application.applicationIconBadgeNumber = 0;
    
    if([application applicationState] == UIApplicationStateActive)
    {
        NSLog(@"App 是在正运行的");
        NSDictionary *dict = [userInfo objectForKey: @"aps"];
        if(dict != nil)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Message" message: [dict objectForKey:@"alert"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [alert show];
            // [dict objectForKey:@"sound"]
        }
    }
    else if([application applicationState] == UIApplicationStateInactive)
    {
        NSLog(@"App 在运行，但是不能接收事件");
        NSDictionary *dict = [userInfo objectForKey: @"aps"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Message" message: [dict objectForKey: @"alert"] delegate: nil cancelButtonTitle: @"Ok" otherButtonTitles: nil];
        [alert show];
    }
}

// send token to the server
// 发送token到自己的服务器
+ (void)sendTokenToServerURLRequest:(NSMutableURLRequest *)request completionBlock: (SendTokenToServerBlock)completed
{
    [NSURLConnection sendAsynchronousRequest:request queue:[self sharedQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
        if(error != nil)
            completed(nil, error);
        else if(error == nil)
        {
            NSError *jsonError = nil;
            id dict = [NSJSONSerialization JSONObjectWithData: data options: 0 error: &jsonError];
            if(jsonError)
                completed(nil, jsonError);
            else
                completed(dict, nil);
        }
    }];
}

+ (instancetype)shareNotificationManager {
    static XHNotificationManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[XHNotificationManager alloc] init];
    });
    return instance;
}

#pragma mark - Left cycle init

- (id)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

#pragma mark - deviceToken

+ (NSOperationQueue *)sharedQueue
{
    static NSOperationQueue *queue = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = [[NSOperationQueue alloc] init];
    });
    return queue;
}

+ (NSString *)deviceToken
{
	return [[NSUserDefaults standardUserDefaults] stringForKey:DeviceTokenKey];
}

+ (void)setDeviceToken:(NSString*)token
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
	[standardUserDefaults setObject:token forKey:DeviceTokenKey];
    [standardUserDefaults synchronize];
}

@end
